<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="false">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row :gutter="48">
          <a-col :span="12" v-if="model.contractPaymentType && (model.contractPaymentType == 'quality' || model.contractPaymentType == 'bail')">
            <a-form-model-item label="款项类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="contractPaymentType">
                <j-dict-select-tag
                  disabled
                  type="list"
                  v-model="model.contractPaymentType"
                  dictCode="contract_payment_type"
                  placeholder="请选择款项类型"/>
              </a-form-model-item>
          </a-col>
          <a-col :span="12" v-else>
            <a-form-model-item label="款项类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="contractPaymentType">
                <j-dict-select-tag
                  :disabled="formDisabled"
                  type="list"
                  v-model="model.contractPaymentType"
                  dictCode="org_payment_type"
                  @back="changeContractPaymentType"
                  placeholder="请选择款项类型"/>
              </a-form-model-item>
          </a-col>
          <!-- <a-col :span="12">
            <a-form-model-item label="款项名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="kxmc">
              <a-input disabled v-model="model.kxmc" placeholder="请输入款项名称"></a-input>
            </a-form-model-item>
          </a-col> -->
          <a-col :span="12">
            <a-form-model-item label="金额" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="je">
              <a-input-number
                :disabled="formDisabled"
                v-model="model.je"
                @blur="jeBlur"
                :precision="2"
                placeholder="请输入金额"
                :min="totalAmount"
                style="width: 100%"/>
              <span v-if="warnShow" style="color: red;margin: 0">
                <span v-if="this.htlx == '1'"> 当前款项已收{{ model.collectMoney }}元，已开票{{ model.invoicePaidAmount }}元, 金额调整不可低于{{ totalAmount }}元</span>
                <span v-if="this.htlx == '2'"> 当前款项已付{{ model.collectMoney }}元 , 金额调整不可低于实付金额</span>
              </span>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="预计款项日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="kxrq">
              <j-date :disabled="formDisabled || collectMoneyStatusDisabled" placeholder="请选择预计款项时间" v-model="model.kxrq" style="width: 100%"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="款项节点说明" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="kxjdsm">
              <a-textarea :disabled="formDisabled || collectMoneyStatusDisabled" v-model="model.kxjdsm" rows="4" placeholder="请输入款项节点说明"/>
            </a-form-model-item>
          </a-col>
          <a-divider style="top:20px;">关联任务</a-divider>
          <a-col :span="24">
            <ErpOmcContractPlanTaskList
              ref="omcContractPlanTaskList"
              :disabled="disabled"
              :totalPrice="model.je"
              :collectMoneyStatus="model.collectMoneyStatus"
              :htlx="htlx"
              :lx="lx"
              :bchte="bchte"
              :projectId="projectId"></ErpOmcContractPlanTaskList>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>
import { getAction } from '@api/manage';
import ErpOmcContractPlanTaskList from './ErpOmcContractPlanTaskList'
export default {
  name: 'ErpOmcContractManagerPlanForm',
  components: {
    ErpOmcContractPlanTaskList
  },
  props: {
    // 表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    },
    // 禁用款项信息
    disablePayment: {
      type: Boolean,
      default: false,
      required: false
    },
    htlx: {
      type: [String, Number],
      default: '',
      required: false
    },
    // 合同的类型， 1 申请，2 变更
    lx: {
      type: [String, Number],
      default: '',
      required: false
    },
    // 合同金额
    bchte: {
      type: Number,
      default: 0
    },
    projectId: {
      type: [String, Number],
      default: '',
      required: false
    },
    // 收付款计划列表
    dataSource: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      totalAmount: 0, // 最小金额
      warnShow: false,
      // 最大和输入金额
      model: {},
      defineModel: {}, // 原始值
      labelCol: {},
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 24 }
      },
      confirmLoading: false,
      validatorRules: {
        contractPaymentType: [
          { required: true, message: '请选择款项类型!' }
        ],
        kxmc: [
          { required: true, message: '请选择款项名称!' }
        ],
        je: [
          { required: true, pattern: /^-?(([0-9]*(\.[0-9]{1,3})$)|([0-9]+$))/, message: '请输入正确的金额!' }
        ],
        kxrq: [
          { required: true, message: '请选择预计款项日期!' }
        ],
        kxjdsm: [
          { required: true, message: '请选择款项节点说明!' }
        ]
      },
      url: {
        add: '/api/erp/omc/contractmanager/erpOmcContractManagerPlan/add',
        edit: '/api/erp/omc/contractmanager/erpOmcContractManagerPlan/edit',
        queryById: '/api/erp/omc/contractmanager/erpOmcContractManagerPlan/queryById',
        queryByApplyId: '/api/erp/omc/contractmanager/erpOmcContractManagerPlanFinal/queryByApplyId'
      }
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
    // 判断当为以应收时，需要禁用除金额外所有的字段
    collectMoneyStatusDisabled() {
      if (this.disabled) {
        return this.disabled
      } else {
        if (this.model.collectMoneyStatus == '已生成') {
          return true
        } else {
          return this.disablePayment
        }
      }
    }
  },
  created() {
    // 备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model));
  },
  methods: {
    add() {
      this.edit(this.modelDefault);
    },
    edit(record) {
      this.$refs['form'].clearValidate();
      this.warnShow = false
      Object.assign(this.$data, this.$options.data())
      // this.$refs.form.resetFields();
      this.model = Object.assign({}, record);
      this.defineModel = Object.assign({}, record); // 备份model原始值
      if (record.planTaskList && record.planTaskList.length) {
        record.planTaskList.forEach((item, index) => {
          item.key = index
        })
      }

      this.$refs.omcContractPlanTaskList.dataSource = record.planTaskList ? (JSON.parse(JSON.stringify(record.planTaskList))) : []
      if (this.model.id) {
          this.$refs.omcContractPlanTaskList.planId = this.model.id
        } else {
          // this.$refs.omcContractPlanTaskList.dataSource = []
          this.$refs.omcContractPlanTaskList.planId = ''
        }
      if (this.model.collectMoney || this.model.invoicePaidAmount) {
        this.warnShow = true
        this.totalAmount = Number(this.model.collectMoney || 0) > Number(this.model.invoicePaidAmount || 0) ? Number(this.model.collectMoney || 0) : Number(this.model.invoicePaidAmount || 0)
      } else {
        if (this.model.id) {
          // 查看合同档案
          getAction(this.url.queryByApplyId, { sealId: this.model.id }).then((res) => {
            if (res.success) {
              // this.dataSource = res.result.records || res.result
              this.model.collectMoney = (res.result && res.result.collectMoney) ? res.result.collectMoney : 0
              this.model.invoicePaidAmount = (res.result && res.result.invoicePaidAmount) ? res.result.invoicePaidAmount : 0
              if (this.model.collectMoney || this.model.invoicePaidAmount) {
                this.warnShow = true
                this.totalAmount = Number(this.model.collectMoney || 0) > Number(this.model.invoicePaidAmount || 0) ? Number(this.model.collectMoney || 0) : Number(this.model.invoicePaidAmount || 0)
              }
            }
          })
        }
      }
      this.visible = true;
    },
    // 选择款项类型
    changeContractPaymentType (val) {
      this.$set(this.model, 'contractPaymentType_dictText', val.text)
      // 款项名称根据款项类型赋值且按照款项1-N排序
      // 判断dataSource数组对象中包含几个model.contractPaymentType相同的对象，然后将其赋值给kxmc
      let count = this.dataSource.filter(item => item.contractPaymentType === val.value).length;
      this.model.kxmc = val.text + (count + 1)
    },
    // 修改金额需要重新计算任务中的款项分配金额
    jeBlur () {
      // let planTaskList = this.$refs.omcContractPlanTaskList.submitForm()
      // if (planTaskList && planTaskList.length > 0) {
      //   if (this.model.je === null || this.model.je === '' || this.model.je === undefined) {
      //     planTaskList.forEach(item => {
      //       item.paymentMoney = 0
      //     })
      //     this.$refs.omcContractPlanTaskList.dataSource = planTaskList
      //   } else {
      //     planTaskList.forEach(item => {
      //       let paymentRate = item.paymentRate
      //       let amount = this.model.je * paymentRate / 100
      //       item.paymentMoney = Math.round((amount + Number.EPSILON) * 100) / 100;
      //     })
      //     this.$refs.omcContractPlanTaskList.dataSource = planTaskList
      //   }
      // }
    },
    submitForm() {
      const that = this;
      // 触发表单验证
      this.$refs.form.validate(valid => {
        if (valid) {
          let count = this.dataSource.filter(item => item.contractPaymentType === this.model.contractPaymentType).length;
          if (this.model.contractPaymentType != 'progress' && count > 0) {
            // 判断是编辑还是新增
            if (this.model.id) {
              // 编辑时需要根据原始值判断是否修改了款项类型
              if (this.defineModel.contractPaymentType !== this.model.contractPaymentType) {
                this.$message.warning(`${this.model.contractPaymentType_dictText}已存在！`);
                return
              }
            } else {
              // 当是新增时则直接提示
              this.$message.warning(`${this.model.contractPaymentType_dictText}已存在！`);
              return
            }
          }
          let planTaskList = this.$refs.omcContractPlanTaskList.submitForm()
          // 判断是否绑定任务
          // 当款项中金额为0 的情况下不需要关联任务
          if (Number(this.model.je) != '0' && !planTaskList.length > 0) {
            this.$message.warning('请添加关联任务信息！');
            this.$emit('unButtonDisable');
            return
          }
          // 判断关联的任务id不能重复
          let taskIdList = planTaskList.map(item => item.taskId)
          let taskIdListSet = new Set(taskIdList)
          if (taskIdList.length !== taskIdListSet.size) {
            this.$message.warning('关联任务不能重复！');
            this.$emit('unButtonDisable');
            return
          }
          let totalRate = 0
          planTaskList.forEach(item => {
            totalRate = Number(item.paymentRate) + totalRate
          })
          // 关联任务款项分配占比需等于100
          // if (this.model.je != '0' && totalRate !== 100) {
          //   that.$message.warning('关联任务款项分配占比需等于100%！');
          //   this.$emit('unButtonDisable');
          //   return
          // }
          this.model.planTaskList = planTaskList
          this.model.taskId_dictText = '' // 首先款项关联任务字段默认为空
          this.model.collectMoneyStatus = this.model.collectMoneyStatus ? this.model.collectMoneyStatus : '未生成' // 新增编辑默认就是未生成
          // 遍历planTaskList数组赋值给taskId_dictText
          this.model.taskId_dictText = planTaskList && planTaskList.length ? (planTaskList.map((obj) => { return obj.categoryName }).join(',')) : '';
          if (!this.model.id) {
            this.model.id = parseInt(Math.random() * 1000000000000);
          }
          that.$emit('ok', this.model);
        }
      })
    }
  }
}
</script>
